var base_query_url = '',
    omics_base_query_uri = '/google-dsapi-svc/addama/datasources/omics',
    tcga_base_query_uri = '/google-dsapi-svc/addama/datasources/omics';
var default_ds = {};
    default_ds['network_uri'] = '/mv_tpp_cleaned_0614_feature_associations/query',
    default_ds['feature_uri'] = '/v_tpp_cleaned_0614_feature_sources/query',
    default_ds['patient_uri'] = '/v_tpp_cleaned_0614_strains/query',
    default_ds['feature_data_uri'] = '/v_tpp_cleaned_0614_strain_values/query';

var query_uri = '/query',
    parsed_data = {network : null,unlocated : null,features : null,unlocated_features:null,located_features:null},
    responses = {network : null},
    patients = {data : null},
    cancer = {sv : null},
    annotations = {'chrom_leng': null,'patients': null};
var quantiled_data = {quantiles : null};
var top_importance_cutoff = 100;
var dataset_annotations = {};

var yeast_gff = {data : null};
var current_data = default_ds;

selectDataset = function(selectedDataSet) {
    current_data = selectedDataSet;
};
var selectedQuantile = '*';
setImportanceQuantile = function(quan){
	if (quan != "*"){
		selectedQuantile = parseFloat(quan);
	}else{
		selectedQuantile = -1;
	}
};
buildGQLQuery = function(args) {
      var query = 'select alias1, alias2, feature1id, feature2id, correlation, importance, pvalue, f1label, f2label';
    var whst = ' where',
    where = whst;

    if (args['f1_type'] != '' && args['f1_type'] != '*') {
        where += (where.length > whst.length ? ' and ' : ' ');
        where += 'f1source = \'' +args['f1_type']+ '\'';
    }
    if (args['f2_type'] != '' && args['f2_type'] != '*') {
        where += (where.length > whst.length ? ' and ' : ' ');
        where += 'f2source = \'' +args['f2_type']+ '\'';
    }

    if (args['f1_label'] != '' && args['f1_label'] != '*' ) {
        where += (where.length > whst.length ? ' and ' : ' ');
        where += '`f1label` like \'%' +args['f1_label']+ '%\'';
    }
     if (args['f2_label'] != '' && args['f2_label'] != '*') {
        where += (where.length > whst.length ? ' and ' : ' ');
        where += '`f2label` like \'%' +args['f2_label']+ '%\'';
    }

    if (args['f1_chr'] != '' && args['f1_chr'] != '*') {
        where += (where.length > whst.length ? ' and ' : ' ');
        where += 'f1chr = \'' +args['f1_chr']+'\'';
    }
    if (args['f2_chr'] != '' && args['f2_chr'] != '*') {
        where += (where.length > whst.length ? ' and ' : ' ');
        where += 'f2chr = \'' +args['f2_chr']+'\'';
    }
    if (args['f1_start'] != '') {
        where += (where.length > whst.length ? ' and ' : ' ');
        where += 'f1start >= ' +args['f1_start'];
    }
    if (args['f2_start'] != '') {
        where += (where.length > whst.length ? ' and ' : ' ');
        where += 'f2start >= ' +args['f2_start'];
    }
    if (args['f1_stop'] != '') {
        where += (where.length > whst.length ? ' and ' : ' ');
        where += 'f1end <= ' +args['f1_stop'];
    }
    if (args['f2_stop'] != '') {
        where += (where.length > whst.length ? ' and ' : ' ');
        where += 'f2end <= ' +args['f2_stop'];
    }
    if (args['importance'] != '') {
        where += (where.length > whst.length ? ' and ' : ' ');
        where += 'importance >= ' +args['importance'];
    }
    if (args['pvalue'] != '') {
        where += (where.length > whst.length ? ' and ' : ' ');
        where += 'pvalue <= ' +args['pvalue'];
    }

    if (args['correlation'] != '') {
        where += (where.length > whst.length ? ' and ' : ' ');
        var corr_fn = args['correlation_fn'];
	if (corr_fn == 'Btw'){
		where += '(correlation >= -' +args['correlation'] + ' and correlation <= ' + args['correlation'] +')';
	}else if (corr_fn == '<='){
		where += '(correlation <= ' + args['correlation'] +')';
	}else if (corr_fn == '>='){
		where += '(correlation >= ' +args['correlation'] +')';
	}else{
        	where += '(correlation >= ' +args['correlation'] + ' or correlation <= -' + args['correlation'] +')';
	}    
   }

  if (args['nonenetwork']){
	where += (where.length > whst.length ? ' and ' : ' ');
	where += 'in_networks = \'N\'';
  }else if (args['allnetwork']){
	where += (where.length > whst.length ? ' and ' : ' ');
	where += 'in_networks = \'Y\'';
  }else {
	if (args['yeastnet']){
  		where += (where.length > whst.length ? ' and ' : ' ');
        	where += 'in_yeastnet = \'Y\'';
  	}	
	if (args['grn']){
        	where += (where.length > whst.length ? ' and ' : ' ');
        	where += 'in_grn = \'Y\'';
  	}
	if (args['genetic']){
        	where += (where.length > whst.length ? ' and ' : ' ');
        	where += 'in_genetic = \'Y\'';
  	}
	if (args['metabolic']){
        	where += (where.length > whst.length ? ' and ' : ' ');
        	where += 'in_metabolic = \'Y\'';
 	 }
	if (args['ppi']){
        	where += (where.length > whst.length ? ' and ' : ' ');
        	where += 'in_ppi = \'Y\'';
  	}
	if (args['pri']){
       		where += (where.length > whst.length ? ' and ' : ' ');
        	where += 'in_pri = \'Y\'';
	} 	 
}
    
    query += (where.length > whst.length ? where : '');
    if (args['order'] != 'Default'){
    	query += ' order by '+args['order'] +' DESC';
    }
    query += ' limit '+args['limit'] + ' label `feature1id` \'f1id\', `feature2id` \'f2id\'';

    return query;
};
function loadFeatureData(link,callback) {
    patients = {data : null};
    var timer =  new vq.utils.SyncDatasources(400,40,callback,patients);
    timer.start_poll();
    var query_str = 'select f1id, f2id, f1alias, f1values, f2alias, f2values ' +
            'where f1id  = ' + link.sourceNode.id + ' and f2id = ' + link.targetNode.id + ' limit 1';
    var patient_query = new google.visualization.Query(base_query_url + tcga_base_query_uri + current_data['feature_data_uri']);
    patient_query.setQuery(query_str);

    function patientQueryHandle(response) {
          if (!response.isError()) {
              patients['data'] = vq.utils.GoogleDSUtils.dataTableToArray(response.getDataTable());
          }  else {
              console.log('Patient Data request failed');
          }
    }
    patient_query.send(patientQueryHandle);
}

function loadYeastGff(chr, callback){
   //select systematic_name, common_name, chr, start, end from yeast_gene_annotations where chr is not null
    var timer = new vq.utils.SyncDatasources(200,40,callback,yeast_gff);
    timer.start_poll();
    var chrom_query = new google.visualization.Query(base_query_url + omics_base_query_uri + '/v_yeast_gene_annotations' + query_uri);
    chrom_query.setQuery("select systematic_name, common_name, chr, start, end where chr = '" +  chr + "'")
    function handleYeastInfoQuery(response) {
            yeast_gff['data'] = vq.utils.GoogleDSUtils.dataTableToArray(response.getDataTable());
    }
    chrom_query.send(handleYeastInfoQuery);
}

function loadAnnotations(callback) {

    annotations = {'chrom_leng': null,'patients': null};
    var timer = new vq.utils.SyncDatasources(100,40,function(){return;},annotations);
    timer.start_poll();
    var chrom_query = new google.visualization.Query(base_query_url + omics_base_query_uri + '/chrom_info/query');
    chrom_query.setQuery("select chr_name, chr_length where species = 'YEAST'");
    function handleChromInfoQuery(response) {
	    annotations['chrom_leng'] = vq.utils.GoogleDSUtils.dataTableToArray(response.getDataTable());
    }
    chrom_query.send(handleChromInfoQuery);
    dataset_annotations = {'datalabels': null};
    var timer = new vq.utils.SyncDatasources(100,40,callback,dataset_annotations);
    timer.start_poll();
    var info_query = new google.visualization.Query(base_query_url + omics_base_query_uri + '/regulome_explorer_dataset/query');
    info_query.setQuery("select dslabel, method, pvalue_cutoff, source");
    function handleDatasetLabelInfoQuery(response) {
            dataset_annotations['datalabels'] = vq.utils.GoogleDSUtils.dataTableToArray(response.getDataTable());
    }
    info_query.send(handleDatasetLabelInfoQuery);

    var patient_query = new google.visualization.Query(base_query_url + tcga_base_query_uri + current_data['patient_uri']);
    patient_query.setQuery('limit 1');
    function patientQueryHandle(response) {
          if (!response.isError()) {
              annotations['patients'] = vq.utils.GoogleDSUtils.dataTableToArray(response.getDataTable())[0]['barcode'].split(':');
          }
    }
    patient_query.send(patientQueryHandle);
}
/*
function loadCancerSV(callback) {

    cancer = {'sv': null};

    var timer = new vq.utils.SyncDatasources(200,40,callback,cancer);
    timer.start_poll();
    var chrom_query = new google.visualization.Query(base_query_url + tcga_base_query_uri + cancer_sv_uri);
    //chrom_query.setQuery('select chr_name, chr_length');
    function handleChromInfoQuery(response) {
        if (!response.isError()) {
              cancer['sv'] = vq.utils.GoogleDSUtils.dataTableToArray(response.getDataTable());
          }
    }
    chrom_query.send(handleChromInfoQuery);
}
*/
function parseNetwork(query_params,callback) {

    parsed_data = {network : null,unlocated : null, features : null,unlocated_features:null,located_features:null};
    var timer = new vq.utils.SyncDatasources(400,40,callback,parsed_data);

    timer.start_poll();
    var importanceSum = 0;
    var importanceValues = [];

    var whole_net = responses['network'].map(function(row) {
        var node1 = row.alias1.split(':');
        var node2 = row.alias2.split(':');
	importanceSum = importanceSum + row.importance;
	importanceValues.push(row.importance);
	//label : node1[2]
           return {node1: {id : row.f1id, source : node1[1], label : row.f1label, chr : node1[3].slice(3),
               start: parseInt(node1[4]), end:node1[5] != '' ? parseInt(node1[5]) : parseInt(node1[4])},
            node2: {id : row.f2id, source : node2[1], label : row.f2label, chr : node2[3].slice(3),
                start: parseInt(node2[4]), end:node2[5] != '' ? parseInt(node2[5]) : parseInt(node2[4])},
            importance : row.importance, correlation:row.correlation, pvalue:row.pvalue};
    }
            );
        var located_responses = whole_net.filter(function(feature) {
        return feature.node1.chr != '' && feature.node2.chr != '';});

        var unlocated_responses =  whole_net.filter(function(feature) {
        return feature.node1.chr == '' || feature.node2.chr == '';});

    var feature_ids = {};
    var features = [];
    whole_net.forEach(function(link) {
        if (feature_ids[link.node1.id] == null) {feature_ids[link.node1.id]=1;features.push(vq.utils.VisUtils.extend({value:link.node1.label},link.node1));    }
        if (feature_ids[link.node2.id] == null) {feature_ids[link.node2.id]=1;features.push(vq.utils.VisUtils.extend({value:link.node2.label},link.node2));    }
    });

    parsed_data['features'] = features;
    parsed_data['network'] = located_responses;
    
    if (selectedQuantile != -1){
        var qsegments = Math.floor(Math.floor(responses['network'].length) * selectedQuantile);
    	top_importance_cutoff = pv.Scale.quantile(importanceValues).quantiles(4).domain()[qsegments];
        importanceMean = importanceSum/responses['network'].length;
    //top_importance_cutoff = importanceMean*1.5;
    //alert("3Q: " + importanceThirdQ + " importanceMean:" + top_importance_cutoff);
    //top_importance_cutff = importanceThirdQ;
    }	
    parsed_data['unlocated'] = unlocated_responses;
    parsed_data['unlocated_features'] = vq.utils.VisUtils.clone(features).filter(function(feature) {
            return feature.chr =='';
        });
    parsed_data['located_features'] = vq.utils.VisUtils.clone(features).filter(function(feature) {
            return feature.chr !='';
        });
}


function loadNetworkData(query_params,callback) {
    response_check={data : null};

    var importance =query_params['importance'],
            correlation =query_params['correlation'];

    if (importance.length < 1) importance = 0;
    if (correlation.length < 1) correlation = 0;

    function handleNetworkQuery(response) {
        response_check['data'] = 1;
        responses = {network : null};
        var timer = new vq.utils.SyncDatasources(400,40,function() {parseNetwork(query_params,callback);},responses);
        timer.start_poll();
        responses['network'] = vq.utils.GoogleDSUtils.dataTableToArray(response.getDataTable());
    }
    var network_query = new google.visualization.Query(base_query_url + tcga_base_query_uri + current_data['network_uri']);
    network_query = new google.visualization.Query(base_query_url + tcga_base_query_uri  + current_data['network_uri']);
    network_query.setQuery(buildGQLQuery(query_params));
    var timer = new vq.utils.SyncDatasources(200,40,function() {return null;},response_check);
    timer.start_poll();
    network_query.send(handleNetworkQuery);
}
